package examination;

import java.sql.*;//导入JDBC标准类库

/**
 * 连接数据库，进行数据库操作。遇到SQLException均抛出
 * @author LeeSin
 */
public class DatabaseBean {
	public DatabaseBean() {
		conn=connect();
	}
	private Connection conn = null;		//数据库连接
	private Statement stmt = null;		//语句句柄
	
	public Connection getConn() {
		return conn;
	}
	public void setConn(Connection conn) {
		this.conn = conn;
	}
	public Statement getStmt() {
		return stmt;
	}
	public void setStmt(Statement stmt) {
		this.stmt = stmt;
	}
	
	/**
	 * 默认无参数数据库连接函数
	 * @return Connection
	 */
	public static Connection connect()
	{
		Connection con = null;
		String driverName = "com.mysql.cj.jdbc.Driver";	//注册MySQL驱动程序
		String dbname = "examination";
		String url = "jdbc:mysql://localhost:3306/"+dbname+"?&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8&useSSL=false";//声明连接数据库的URL
		String username="root";
		String password="1234";
		
		try
		{
			Class.forName(driverName);	
			//System.out.println("加载成功");
		}catch(ClassNotFoundException e)
		{
			System.out.print("Error loading Driver,不能加载驱动程序！");
		}
		try
		{
			con = DriverManager.getConnection(url,username,password);
		}
		catch(SQLException er)
		{
			System.out.print("Error getConnection,不能连接数据库！");
		}
		return con;
	}
	
	/**
	 * DML查询部分
	 * 执行查询操作数据库函数
	 * @param sql
	 * @return ResultSet
	 */
	public ResultSet executeQuery(String sql)
	{
		//TODO
		ResultSet rst = null;
		try
		{
			stmt=conn.createStatement();	//建立Statement对象
			rst=stmt.executeQuery(sql);		//执行SQL语句
		}
		catch(SQLException ex)
		{
			System.err.print("Error Execute Query:"+ex.getMessage());
			return null;
		}
		return rst;
	}
	
	/**
	 * DML更新部分
	 * 执行增删改查操作数据库函数
	 * @param sql
	 * @return boolean
	 */
	
	public boolean executeUpdate(String sql) {
		//TODO
		try
		{
			stmt=conn.createStatement();	//建立Statement对象
			stmt.executeUpdate(sql);		//执行SQL语句
			
		}
		catch(SQLException ex)
		{
			System.err.println(ex.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * 关闭连接资源
	 */
	public void close() {
		//TODO
		try
		{
			//按道理还需要关闭ResultSet，但查询结果集生命周期为函数，故此处略去
			
			if(stmt!=null) {
				stmt.close();
			}
			
			conn.close();
		}
		catch(SQLException ex){
			System.err.println(ex.getMessage());
		}
	}
}
